<template>
  <div class="order-detail-container">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>订单详情</span>
          <el-button @click="goBack">返回列表</el-button>
        </div>
      </template>

      <div v-loading="loading">
        <el-descriptions title="订单信息" :column="2" border>
          <el-descriptions-item label="订单号">{{
            orderInfo.id
          }}</el-descriptions-item>
          <el-descriptions-item label="用户账号">{{
            orderInfo.user ? orderInfo.user.nick_name : ""
          }}</el-descriptions-item>
          <el-descriptions-item label="用户ID">{{
            orderInfo.user ? orderInfo.user_id : ""
          }}</el-descriptions-item>
          <el-descriptions-item label="用户手机">
            {{
              orderInfo.user && orderInfo.user.mobile
                ? userStore.isTest
                  ? maskMobile(orderInfo.user.mobile)
                  : orderInfo.user.mobile
                : "未填写"
            }}
          </el-descriptions-item>
          <el-descriptions-item label="套餐名称">{{
            orderInfo.plan ? orderInfo.plan.name : ""
          }}</el-descriptions-item>
          <el-descriptions-item label="订单金额"
            >¥{{ orderInfo.amount }}</el-descriptions-item
          >
          <el-descriptions-item label="支付方式">{{
            getPayTypeName(orderInfo.payment?.payment_type)
          }}</el-descriptions-item>
          <el-descriptions-item label="订单状态">
            <el-tag :type="getStatusType(orderInfo.status)">
              {{ getStatusName(orderInfo.status) }}
            </el-tag>
          </el-descriptions-item>

          <el-descriptions-item label="支付时间">{{
            orderInfo.paid_time
          }}</el-descriptions-item>
          <el-descriptions-item label="微信回调时间">{{
            orderInfo.notify_time
          }}</el-descriptions-item>
          <el-descriptions-item label="微信预支付ID">{{
            orderInfo.prepay_id
          }}</el-descriptions-item>
          <el-descriptions-item label="微信支付交易号">{{
            orderInfo.transaction_id
          }}</el-descriptions-item>
          <el-descriptions-item label="商品使用次数">{{
            orderInfo.times
          }}</el-descriptions-item>
          <el-descriptions-item label="实际支付金额">{{
            orderInfo.total_fee
          }}</el-descriptions-item>

          <el-descriptions-item label="创建时间">{{
            orderInfo.create_time
          }}</el-descriptions-item>
          <el-descriptions-item label="支付时间" v-if="orderInfo.paid_at">{{
            orderInfo.paid_at
          }}</el-descriptions-item>
          <el-descriptions-item label="订单备注" :span="2">{{
            orderInfo.remark || "无"
          }}</el-descriptions-item>
        </el-descriptions>

        <div class="action-box" v-if="orderInfo.status !== undefined">
          <el-button
            type="primary"
            v-if="orderInfo.status === 0"
            @click="handleConfirmPayment"
            :disabled="userStore.isTest"
          >
            确认支付
          </el-button>
          <el-button
            type="warning"
            v-if="orderInfo.status === 1"
            @click="handleRefund"
            :disabled="userStore.isTest"
          >
            申请退款
          </el-button>
          <el-button
            type="danger"
            v-if="orderInfo.status === 0"
            @click="handleCancel"
            :disabled="userStore.isTest"
          >
            取消订单
          </el-button>
        </div>

        <div class="remark-box">
          <el-divider content-position="left">添加备注</el-divider>
          <el-form :model="remarkForm" :rules="remarkRules" ref="remarkFormRef">
            <el-form-item prop="content">
              <el-input
                v-model="remarkForm.content"
                type="textarea"
                :rows="3"
                placeholder="请输入订单备注"
                :disabled="userStore.isTest"
              />
            </el-form-item>
            <el-form-item>
              <el-button
                type="primary"
                @click="submitRemark"
                :disabled="userStore.isTest"
                >提交备注</el-button
              >
            </el-form-item>
          </el-form>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from "vue";
import { useRoute, useRouter } from "vue-router";
import { ElMessage, ElMessageBox } from "element-plus";
import {
  getOrderDetail,
  addOrderRemark,
  updateOrderStatus,
  confirmOrderPayment,
} from "@/api/orders";
import { useUserStore } from "@/store/user";

const route = useRoute();
const router = useRouter();
const userStore = useUserStore();
const loading = ref(false);
const remarkFormRef = ref(null);
const orderInfo = ref({});
const orderId = ref(route.params.id || 0);

// 备注表单
const remarkForm = reactive({
  content: "",
});

// 备注表单验证规则
const remarkRules = {
  content: [{ required: true, message: "请输入备注内容", trigger: "blur" }],
};

// 获取订单详情
const getDetail = async () => {
  console.log(orderId.value);

  if (!orderId.value) {
    ElMessage.error("订单ID不能为空");
    return;
  }

  loading.value = true;
  try {
    const res = await getOrderDetail(orderId.value);
    if (res.code === 0) {
      if (res.data.prepay_id?.includes("prepay_id=")) {
        res.data.prepay_id = res.data.prepay_id.replace("prepay_id=", "");
      }
      orderInfo.value = res.data;
    } else {
      ElMessage.error(res.message || "获取订单详情失败");
    }
  } catch (error) {
    console.error("获取订单详情失败", error);
    ElMessage.error("获取订单详情失败");
  } finally {
    loading.value = false;
  }
};

// 返回列表页
const goBack = () => {
  router.push("/order/list");
};

// 提交备注
const submitRemark = async () => {
  if (!remarkFormRef.value) return;

  // 检查权限
  if (userStore.isTest) {
    ElMessage.warning("测试账号不能添加备注");
    return;
  }

  await remarkFormRef.value.validate(async (valid) => {
    if (!valid) return;

    try {
      const res = await addOrderRemark(orderId.value, remarkForm.content);
      if (res.code === 0) {
        ElMessage.success("添加备注成功");
        remarkForm.content = "";
        getDetail();
      } else {
        ElMessage.error(res.message || "添加备注失败");
      }
    } catch (error) {
      console.error("添加备注失败", error);
      ElMessage.error("添加备注失败");
    }
  });
};

// 确认支付
const handleConfirmPayment = () => {
  // 检查权限
  if (userStore.isTest) {
    ElMessage.warning("测试账号不能执行确认支付操作");
    return;
  }

  ElMessageBox.confirm(`确认要将订单标记为已支付吗?`, "提示", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      try {
        const res = await confirmOrderPayment(orderId.value);
        if (res.code === 0) {
          ElMessage.success("操作成功");
          getDetail();
        } else {
          ElMessage.error(res.message || "操作失败");
        }
      } catch (error) {
        console.error("操作失败", error);
        ElMessage.error("操作失败");
      }
    })
    .catch(() => {
      // 取消操作
    });
};

// 申请退款
const handleRefund = () => {
  // 检查权限
  if (userStore.isTest) {
    ElMessage.warning("测试账号不能执行退款操作");
    return;
  }

  ElMessageBox.confirm(`确认要对该订单进行退款操作吗?`, "提示", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      try {
        const res = await updateOrderStatus(orderId.value, 3);
        if (res.code === 0) {
          ElMessage.success("退款操作成功");
          getDetail();
        } else {
          ElMessage.error(res.message || "操作失败");
        }
      } catch (error) {
        console.error("操作失败", error);
        ElMessage.error("操作失败");
      }
    })
    .catch(() => {
      // 取消操作
    });
};

// 取消订单
const handleCancel = () => {
  // 检查权限
  if (userStore.isTest) {
    ElMessage.warning("测试账号不能执行取消订单操作");
    return;
  }

  ElMessageBox.confirm(`确认要取消该订单吗?`, "提示", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      try {
        const res = await updateOrderStatus(orderId.value, 2);
        if (res.code === 0) {
          ElMessage.success("订单已取消");
          getDetail();
        } else {
          ElMessage.error(res.message || "操作失败");
        }
      } catch (error) {
        console.error("操作失败", error);
        ElMessage.error("操作失败");
      }
    })
    .catch(() => {
      // 取消操作
    });
};

// 获取套餐类型名称
const getPlanTypeName = (type) => {
  const typeMap = {
    month: "月套餐",
    quarter: "季套餐",
    year: "年套餐",
    permanent: "永久套餐",
  };
  return typeMap[type] || "未知";
};

/**
 * 获取支付方式中文名称
 * @param {string} type - 支付方式代码，如 WXPAY、ALIPAY 等
 * @returns {string} 支付方式中文名称，未知则返回“未知”
 */
const getPayTypeName = (type) => {
  const payTypes = {
    WXPAY: "微信支付",
    ALIPAY: "支付宝支付",
    OTHERS: "微信零钱", // 兼容旧字段
    CMB_DEBIT: "招商银行借记卡",
    COMM_DEBIT: "交通银行借记卡",
    ICBC_DEBIT: "工商银行借记卡",
    ABC_DEBIT: "农业银行借记卡",
    BOC_DEBIT: "中国银行借记卡",
    CCB_DEBIT: "建设银行借记卡",
    SPDB_DEBIT: "浦发银行借记卡",
    BOC_CREDIT: "中国银行信用卡",
    ALIPAY_CREDIT: "支付宝信用卡",
    UNIONPAY: "银联支付",
    UNIONPAY_CREDIT: "银联信用卡",
    UNIONPAY_DEBIT: "银联借记卡",
    JD_PAY: "京东支付",
    JD_CREDIT: "京东白条",
    JD_DEBIT: "京东借记卡",
    QQ_WALLET: "QQ钱包",
    JD_WALLET: "京东钱包",
    WECHAT_WALLET: "微信钱包",
    BILIBILI: "哔哩哔哩支付",
    TOUTIAO: "今日头条支付",
    KUAISHOU: "快手支付",
    DOUYIN: "抖音支付",
    MEITUAN: "美团支付",
    DINGDING: "钉钉支付",
    BAIDU: "百度支付",
    ALIPAY_WALLET: "支付宝钱包",
    ALIPAY_QR: "支付宝扫码支付",
    WXPAY_QR: "微信扫码支付",
    WXPAY_APP: "微信APP支付",
    ALIPAY_APP: "支付宝APP支付",
    ALIPAY_WAP: "支付宝手机网页支付",
    WXPAY_WAP: "微信手机网页支付",
    ALIPAY_SCAN: "支付宝扫码支付",
    WXPAY_SCAN: "微信扫码支付",
    ALIPAY_TRANSFER: "支付宝转账",
    WXPAY_TRANSFER: "微信转账",
    ALIPAY_INVOICE: "支付宝发票",
    WXPAY_INVOICE: "微信发票",
    ALIPAY_QRCODE: "支付宝二维码支付",
    WXPAY_QRCODE: "微信二维码支付",
    ALIPAY_OFFLINE: "支付宝线下支付",
    WXPAY_OFFLINE: "微信线下支付",
    ALIPAY_POS: "支付宝POS机支付",
    WXPAY_POS: "微信POS机支付",
    ALIPAY_MOBILE: "支付宝手机支付",
    WXPAY_MOBILE: "微信手机支付",
    ALIPAY_WEB: "支付宝网页支付",
    WXPAY_WEB: "微信网页支付",
    ALIPAY_APP_QR: "支付宝APP扫码支付",
    WXPAY_APP_QR: "微信APP扫码支付",
    ALIPAY_WAP_QR: "支付宝手机网页扫码支付",
    WXPAY_WAP_QR: "微信手机网页扫码支付",
    ALIPAY_WALLET_QR: "支付宝钱包扫码支付",
    WXPAY_WALLET_QR: "微信钱包扫码支付",
    ALIPAY_QR_CODE: "支付宝二维码支付",
    WXPAY_QR_CODE: "微信二维码支付",
    ALIPAY_OFFLINE_QR: "支付宝线下二维码支付",
    WXPAY_OFFLINE_QR: "微信线下二维码支付",
    ALIPAY_POS_QR: "支付宝POS机二维码支付",
    WXPAY_POS_QR: "微信POS机二维码支付",
    ALIPAY_MOBILE_QR: "支付宝手机二维码支付",
    PAYPAL: "PayPal支付",
  };

  if (typeof type !== "string") return "未知";

  // 支持大小写转换
  return payTypes[type.toUpperCase()] || "未知";
};

// 获取状态名称
const getStatusName = (status) => {
  const statusMap = {
    PENDING: "待支付",
    PAID: "已支付",
    CLOSED: "已取消",
    3: "已退款",
  };
  return statusMap[status] || "未知";
};
// 获取状态对应的标签类型
const getStatusType = (status) => {
  const statusTypeMap = {
    PENDING: "待支付",
    PAID: "已支付",
    CLOSED: "已关闭",
  };
  return statusTypeMap[status] || "";
};

// 手机号脱敏处理
const maskMobile = (mobile) => {
  if (!mobile) return "";
  return mobile.replace(/^(\d{3})\d{4}(\d{4})$/, "$1****$2");
};

onMounted(() => {
  getDetail();
});
</script>

<style scoped>
.order-detail-container {
  padding: 20px;
  height: 100%;
}
.box-card {
  height: 100%;
}
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.action-box {
  margin-top: 20px;
  margin-bottom: 20px;
}
.remark-box {
  margin-top: 30px;
}
</style>
